#!/usr/bin/env python3
"""
调试路径检测脚本
用于测试打包后的exe环境中的路径检测逻辑
"""

import sys
import os
from pathlib import Path

def debug_path_detection():
    """调试路径检测逻辑"""
    print("=" * 60)
    print("路径检测调试")
    print("=" * 60)
    
    # 1. 基本环境信息
    print("基本环境信息:")
    print(f"sys.executable: {sys.executable}")
    print(f"sys.argv[0]: {sys.argv[0]}")
    print(f"__file__: {__file__ if '__file__' in globals() else 'N/A'}")
    print(f"os.getcwd(): {os.getcwd()}")
    print(f"Path.cwd(): {Path.cwd()}")
    
    # 2. 检测运行环境
    is_frozen = getattr(sys, 'frozen', False)
    print(f"\n运行环境:")
    print(f"is_frozen: {is_frozen}")
    
    # 3. 获取应用根目录
    if is_frozen:
        # 打包后的exe环境
        app_root = Path(sys.executable).parent
        print(f"app_root (exe): {app_root}")
    else:
        # 开发环境
        if '__file__' in globals():
            app_root = Path(__file__).parent
        else:
            app_root = Path.cwd()
        print(f"app_root (dev): {app_root}")
    
    # 4. 定义搜索目录
    search_dirs = [
        app_root,                    # 应用根目录
        app_root.parent,             # 上级目录  
        Path.cwd(),                  # 当前工作目录
    ]
    
    print(f"\n搜索目录:")
    for i, search_dir in enumerate(search_dirs, 1):
        exists = search_dir.exists()
        print(f"{i}. {search_dir} {'✅' if exists else '❌'}")
        if exists:
            # 列出目录内容
            try:
                files = list(search_dir.glob("*.py"))
                if files:
                    print(f"   Python文件: {[f.name for f in files[:5]]}")
                else:
                    print(f"   无Python文件")
            except Exception as e:
                print(f"   无法访问: {e}")
    
    # 5. 搜索WMS服务文件
    print(f"\n搜索WMS服务文件:")
    
    # Python脚本候选
    script_candidates = [
        "wms_service.py",
        "main_server.py",
        "main.py"
    ]
    
    found_files = []
    
    for search_dir in search_dirs:
        if not search_dir.exists():
            continue
            
        print(f"\n在 {search_dir} 中搜索:")
        for script_name in script_candidates:
            script_path = search_dir / script_name
            if script_path.exists():
                print(f"  ✅ 找到: {script_path}")
                found_files.append(script_path)
            else:
                print(f"  ❌ 未找到: {script_path}")
    
    # 6. 总结结果
    print(f"\n" + "=" * 60)
    print("检测结果总结:")
    print("=" * 60)
    
    if found_files:
        print("找到的WMS服务文件:")
        for file_path in found_files:
            print(f"  {file_path}")
        
        # 推荐使用的文件
        recommended = found_files[0]
        print(f"\n推荐使用: {recommended}")
        
        # 构建服务路径
        python_exe = sys.executable
        service_path = f'"{python_exe}" "{recommended}"'
        print(f"服务路径: {service_path}")
        
        return True, service_path
    else:
        print("❌ 未找到任何WMS服务文件")
        print("请确保WMS主程序已正确部署")
        return False, None

if __name__ == "__main__":
    success, path = debug_path_detection()
    print(f"\n测试结果: {'成功' if success else '失败'}")
    if path:
        print(f"服务路径: {path}") 